//
//  XYComposeToolBar.swift
//  WeiboSourceCode
//
//  Created by 周星宇 on 16/1/5.
//  Copyright © 2016年 cn.weibo. All rights reserved.
//

import UIKit

enum XYComposeToolBarBtnType: Int {
    
    case Picture = 1000
    case Mention = 1001
    case Trend = 1002
    case Emoticon = 1003
    case Add = 1004
}
class XYComposeToolBar: UIStackView {
    
    
    var isSystemKeyBoard: Bool = true {
        
        didSet {
            let btn = viewWithTag(XYComposeToolBarBtnType.Emoticon.rawValue) as! UIButton
            // 设置图片的默认名字
            var imageNamed = "compose_keyboardbutton_background"
            if isSystemKeyBoard {
                // 如果是系统键盘，更改图片名字
                imageNamed = "compose_emoticonbutton_background"
            }
            
            btn.setImage(UIImage(named: imageNamed), forState: UIControlState.Normal)
            btn.setImage(UIImage(named: "\(imageNamed)_highlighted"), forState: UIControlState.Highlighted)
        }
    }
    // 外界的接口闭包
    var composeToolBarBtnOnClickClosure: ((type: XYComposeToolBarBtnType) -> ())?
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func  setUpUI() {
        backgroundColor = UIColor.redColor()
        // 设置填充模式
        distribution = .FillEqually
        addChildBtn("compose_toolbar_picture", type: .Picture)
        addChildBtn("compose_mentionbutton_background", type: .Mention)
        addChildBtn("compose_trendbutton_background", type: .Trend)
        addChildBtn("compose_emoticonbutton_background", type: .Emoticon)
        addChildBtn("compose_add_background", type: .Add)
        
    }
    private func addChildBtn(imageName:String,type: XYComposeToolBarBtnType) {
        
        let button = UIButton()
        // 给按钮添加点击事件
        button.addTarget(self, action: "childButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        // 设置不同状态的图片
        button.setImage(UIImage(named: imageName), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "\(imageName)_highlighted"), forState: UIControlState.Highlighted)
        // 设置背景颜色
        button.backgroundColor = UIColor(patternImage: UIImage(named: "compose_toolbar_background")!)
        // 取出枚举的真实数值
        button.tag = type.rawValue
        // 只有使用addArrangedSubview 才会自动添加约束
        addArrangedSubview(button)
    }
    @objc private func childButtonClick(btn:UIButton) {
        
        composeToolBarBtnOnClickClosure?(type: XYComposeToolBarBtnType(rawValue: btn.tag)!)
    }
    
}
